import {
  getUserShopCarInfoData
} from '../../http/api model/shopCar'

import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';

Page({
  data: {
    active: 0,
    imageURL: '../../images/珍珠奶茶.png',
    shopCar: [],
    priceSum: 0,
    OrdersMade: [],
    OrdersProgress: [],
    OrdersDone: [],
    loading: true
  },
  // 购物车首次加载
  onLoad(options) {
    this.getOrdersMade()
    if (!wx.getStorageSync('openID')) {
      // console.log("----------没有登录哦！--------");
      setTimeout(() => {
        wx.redirectTo({
          url: "/pages/me/me"
        }, 0)
      })
    }
    if (options && options.active) {
      this.setData({
        active: Number(options.active)
      })
    }
    this.updataShopCar()
    this.loadCar()
  },
  onChange(event) {
    this.getOrdersMade()
    this.updataShopCar()
  },

  goshopList() {
    wx.switchTab({
      url: "/pages/storeInfo/storeInfo"
    })
  },
  // 购物车页面每次进入
  onShow() {
    this.loadCar()
    if (!wx.getStorageSync('openID')) {
      // console.log("----------没有登录哦！--------");
      setTimeout(() => {
        wx.redirectTo({
          url: "/pages/me/me"
        }, 0)
      })
      return
    }
    this.getOrdersMade()
    this.updataShopCar()
  },
  // 更新购物车数据
  updataShopCar() {
    getUserShopCarInfoData(wx.getStorageSync('openID')).then(res => {
      this.setData({
        shopCar: res.data || [],
        loading: false
      })
    })
  },
  goToPlaceOrder(e) {
    let id = e.currentTarget.dataset.sd
    const {
      shopCar
    } = this.data;
    const selectShopOrder = shopCar.find(n => n.id == id);
    wx.setStorageSync('shopCarINFO', selectShopOrder)
    wx.navigateTo({
      url: `/pages/placeOrder/placeOrder?shopId=${id}`
    })
  },
  // 删除购物车某一个商品
  onClose(e) {
    const {
      id
    } = e.currentTarget.dataset;
    Dialog.confirm({
        title: `确定删除吗？`,
        message: '',
      })
      .then(() => {
        let shopCar = wx.getStorageSync('shopCar');
        delete shopCar[id];
        wx.setStorageSync('shopCar', shopCar);
        this.updataShopCar()
      })
      .catch(() => {});

  },
  getOrdersMade() {
    let userid = wx.getStorageSync('openID');
    wx.request({
      url: `http://localhost:5555/users/getUserOrder?userid=${userid}`,
      method: "get",
      success: (res) => {
        let OrdersProgress = [];
        let OrdersDone = [];
        let data = res.data.data;
        data = data.map(n => {
          return {
            ...n,
            createTime: formatTime(n.createTime)
          }
        })

        function formatTime(n) {
          const time = new Date(n).getTime();
          //datetime是拿到的时间戳
          var date = new Date(time); //时间戳为10位需*1000，时间戳为13位的话不需乘1000 
          var year = date.getFullYear(),
            month = ("0" + (date.getMonth() + 1)).slice(-2),
            sdate = ("0" + date.getDate()).slice(-2),
            hour = ("0" + date.getHours()).slice(-2),
            minute = ("0" + date.getMinutes()).slice(-2),
            second = ("0" + date.getSeconds()).slice(-2);
          // 拼接
          var result = year + "-" + month + "-" + sdate + " " + hour + ":" + minute + ":" + second;
          // 返回
          return result;
        }
        for (let i = 0; i < data.length; i++) {
          if (data[i].status == 0 || data[i].status == 2) {
            OrdersProgress.push(data[i]);
          } else if (data[i].status == 1 || data[i].status == 3) {
            OrdersDone.push(data[i])
          }
        }
        this.setData({
          OrdersMade: data,
          OrdersDone,
          OrdersProgress
        })
      },
      fail(err) {}
    })
  },
  loadCar() {
    let arr = Object.keys(this.data.shopCar);
  },
  goorderCallWait(e) {
    const {
      orderid: id,
      done
    } = e.currentTarget.dataset;
    const {
      OrdersDone,
      OrdersProgress
    } = this.data;
    wx.setStorageSync('ORDER', [...OrdersDone, ...OrdersProgress].find(n => n.orderid == id))
    wx.navigateTo({
      url: `/pages/orderCallWait/orderCallWait?orderid=${e.currentTarget.dataset.orderid}&done=${done}`
    })
  },
});